﻿using ETask.Api.Dtos;
using ETask.Api.Mappers;
using ETask.Api.Models;
using ETask.Api.Repositories;

namespace ETask.Api.Services
{
    public class ProjectDocService : GenericService<ProjectDoc, ProjectDocDto, CreateProjectDocDto, UpdateProjectDocDto>, IProjectDocService
    {
        private readonly IProjectDocRepository _repository;

        private readonly ITaskFileRepository _taskFileRepository;

        public ProjectDocService(IProjectDocRepository repository, ITaskFileRepository taskFileRepository, GenericMapper<ProjectDoc, ProjectDocDto, CreateProjectDocDto, UpdateProjectDocDto> mapper) : base(repository, mapper)
        {
            _repository = repository;
            _taskFileRepository = taskFileRepository;
        }

        public async Task<ApiResponse> GetDocListAsync(ProjectDocListParams listParams)
        {
            var result = await _repository.GetListAsync(listParams);
            return ApiResponse.Ok(result);
        }

        public async Task<ApiResponse> GetFiles(TaskFileListParams listParams)
        {
            var result = await _taskFileRepository.GetListByProject(listParams);
            return ApiResponse.Ok(result);
        }

        public async Task<ApiResponse> GetInfoById(int id)
        {
            var result = await _repository.GetInfoByIdAsync(id);
            return ApiResponse.Ok(result);
        }

        public async Task<ApiResponse> GetTips(int projectId)
        {
            var tips = await _repository.GetTipsAsync(projectId);

            var allKeywords = tips
                .Where(t => !string.IsNullOrWhiteSpace(t.Key))
                .SelectMany(t => t.Key.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                .Select(keyword => keyword.Trim()) 
                .Where(keyword => !string.IsNullOrWhiteSpace(keyword));

            var result = allKeywords
                .GroupBy(keyword => keyword)
                .Select(group => new ItemDto
                {
                    Key = group.Key,
                    Count = group.Count()
                })
                .OrderByDescending(dto => dto.Count) 
                .ToList();

            return ApiResponse.Ok(result);

        }
    }
}
